package kr.hkit.powerjava.chapter14; //340예제

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Cards extends JPanel {
	CardLayout layout;
	
	public Cards() {
		layout = new CardLayout();
		setLayout(layout);
		for (int i = 1; i <=10; i++) {
			add(new JButton("현재 카드 번호" + i + "입니다."));
		}
	}
}

class CardFrame extends JFrame { //책에는 actionlistener 구현했음
	Cards card;
	
	public CardFrame(String title) {
		super(title);
		initialize();
	}

	private void initialize() {
		setSize(400, 200);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JPanel panel = new JPanel(new GridLayout(0,5,10,0));
		addButton("<<",panel);
		addButton("<",panel);
		addButton(">",panel);
		addButton(">>",panel);
		addButton("종료",panel);
		
		add(panel, BorderLayout.NORTH); //보더아웃으로
		
		card = new Cards();
		add(card, BorderLayout.CENTER);
		
/*		JPanel card = new JPanel(new CardLayout());
		for (int i = 1; i <=10; i++) {
			card.add(new JButton("현재 카드 번호" + i + "입니다."));
		} //이렇게 하면 위의 Cards 메소드 안만들어도됨
		add(card, BorderLayout.CENTER);*/
		
		setVisible(true);
	}

	private void addButton(String text, JPanel panel) {
		JButton btn = new JButton(text);
		btn.addActionListener(listener); //이벤트 발생시 밑의 메소드 자동 호출됨
		panel.add(btn);
	}
	
	ActionListener listener = new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent e) {
			/*System.out.println("getActionCommande(): " + e.getActionCommand());
			System.out.println("getSource(): " + e.getSource());
			System.out.println("getID(): " + e.getID());*/
			
			if (e.getActionCommand().equals("종료")){
				System.exit(0);
			} else if (e.getActionCommand().equals("<<")){
				card.layout.first(card);
			} else if (e.getActionCommand().equals("<")){
				card.layout.previous(card);
			} else if (e.getActionCommand().equals(">")){
				card.layout.next(card);
			} else {
				card.layout.last(card);
			}
		}
	};
}

public class CardLayoutEx {
	public static void main(String[] args) {
		new CardFrame("CardLayout 예제");
	}
}
